<?php
App::uses('AppController', 'Controller');

/**
 * Animes Controller
 *
 * @property Anime $Anime
 */
class AnimesController extends AppController {
    public $components = array('RequestHandler','Session');
    public $helpers = array('Function','Msg','Js');
    public $paginate = array('limit'=>10);

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->layout='index';

        /**
         * Adicinado filtro
         */
        $options = array('0'=>'Destivado','1'=>'Ativo');
        $this->Filter->addFilters(
            array(
                'filter1' => array(
                    'Anime.name' => array(
                        'operator' => 'LIKE',
                        'value' => array(
                            'before' => '%', // opcional
                            'after'  => '%'  // opcional
                        )
                    )
                ),
                't_status'=>array(
                    'Anime.status'=>array(
                        'select'=>$this->Filter->select('Status',$options)
                    )
                )
            )
        );

        $this->Filter->setPaginate('order', 'Anime.id DESC'); // opcional
        //$this->Filter->setPaginate('limit', 10);              // opcional

        // Define conditions
        $this->Filter->setPaginate('conditions', $this->Filter->getConditions());

        $this->Anime->recursive = 0;
        $animes = $this->paginate();

        $menu_cad = 'active';
        $active_anime = 'active';
        $this->set(compact('animes','username','menu_cad','active_anime'));
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        $this->layout = false;
        if (!$this->Anime->exists($id)) {
            $this->showMessage('O anime não foi encontrado',array('type'=>'error','close'=>true,'title'=>'ERROR:'));
            $this->redirect(array('action'=>'index'));
        }
        $options = array('conditions' => array('Anime.' . $this->Anime->primaryKey => $id));
        $this->set('anime', $this->Anime->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add()
    {
        $this->layout = 'cadastros';
        $new = 1;
        if ($this->request->is('post')) {
            $this->Anime->create();
            if ($this->Anime->saveAll($this->request->data,array('deep'=>true,'validate'=>false)))
            {
                $this->showMessage('Anime salvo com sucesso.',array('type'=>'successo','close'=>true,'title'=>'CONCLUIDO:'));
                $this->redirect(array('action' => 'index'));

            } else {
                $this->showMessage('Não foi possivel salvar o Anime',array('type'=>'error','close'=>true,'title'=>'ERROR:'));
            }
//            debug($this->Anime->validationErrors);
        }
        $genres = $this->Anime->Genre->find('list');
        $this->set(compact('genres','new'));
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        $this->layout = 'cadastros';
        $new = '';

        if (!$this->Anime->exists($id))
        {
           $this->showMessage('O anime não foi encontrado',array('type'=>'error','close'=>true,'title'=>'ERROR:'));
            $this->redirect(array('action'=>'index'));
        }

        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Anime->saveAll($this->request->data,array('deep'=>true,'validate'=>false))) {
                $this->showMessage(' Anime Alterado com sucesso.',array('type'=>'success','close'=>true,'title'=>'ALTERAÇÃO:'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->showMessage('Não foi possivel salvar as alterações no Anime.',array('type'=>'error','close'=>true,'title'=>'ERROR:'));
            }
//            debug($this->Anime->validationErrors);
        } else {
            $options = array('conditions' => array('Anime.' . $this->Anime->primaryKey => $id));
            $this->request->data = $this->Anime->find('first', $options);
        }
        $seasons = $this->Anime->Season->find('all',array('conditions'=>array('Season.anime_id'=>$id)));
        $genres = $this->Anime->Genre->find('list');
        $this->set(compact('genres','seasons','new'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        $this->Anime->id = $id;
        if (!$this->Anime->exists()) {
            $this->showMessage('O anime não foi encontrado',array('type'=>'error','close'=>true,'title'=>'ERROR:'));
            $this->redirect(array('action'=>'index'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Anime->delete()) {
            $this->showMessage('Anime deletado com sucesso.',array('type'=>'success','close'=>true,'title'=>'EXCLUS&Atilde;O:'));
            $this->redirect(array('action' => 'index'));
        }
        $this->showMessage('Não foi possivel excluido o anime.',array('type'=>'error','close'=>true,'title'=>'EXCLUS&Atilde;O:'));
        $this->redirect(array('action' => 'index'));
    }


    public function status($id=null,$status=null)
    {
        $this->autoRender = false;
        $this->Anime->id = $id;
        if(!$this->Anime->exists($id))
        {
            $this->Session->setFlash('error');
            return null;
        }
        if(!empty($status) || $status == 0)
        {
            if($this->Anime->saveField('status',$status))
            {
                if($status == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return null;
            }
        }else{
            return null;
        }
    }

    public function autoComplete()
    {
        $this->autoRender = false;
        $this->RequestHandler->respondAs('json');

        $query = $this->request->query['q'];
        $animes = $this->Anime->find('all',array('conditions'=>array('Anime.name LIKE'=>'%'.$query.'%')));

        $result = array();
        foreach($animes as $key=>$anime)
        {
            array_push($result,$anime['Anime']['name']);
        }
        $animes = $result;

        echo json_encode($animes);
    }

    public function FormSeasons()
    {
        $this->layout = false;
        $this->loadModel('Situation');
        $situations = $this->Situation->find('list',array('conditions'=>array('status'=>1)));
        $this->loadModel('Rating');
        $ratings = $this->Rating->find('list',array('conditions'=>array('status'=>1)));
        $this->set(compact('situations', 'ratings'));
    }

}
